import React from 'react';
import { message } from 'antd';
import { connect } from 'umi';
import moment from 'moment';
import classnames from 'classnames';

import { isSuccess } from '@/utils/request';
import { salaryRecheck } from '@/services/salaryManage/salaryCalculate';
import { salaryStatisticsService as service } from '@/services/salaryManage/statistics';
import { goToSalaryStatisticsDetail } from '@/pages/SalaryManage/utils/pageNavigateUtil';

import modelType from '@/pages/SalaryManage/constant/commonModelType';
import modelFactory from '@/pages/SalaryManage/Statistics/statisticsModelFactory';
import { ColumnProcessor, CommonColumnInterceptor } from '@/pages/SalaryManage/SalaryCalculate/Recheck/ColumnProcessor';

import EmployeeNameWrapper from '@/pages/SalaryManage/components/EmployeeNameWrapper';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import {
    numberFilter,
    orFilter,
    summaryFieldChooser
} from '@/pages/SalaryManage/SalaryCalculate/Recheck/SummaryProcessor';
import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';

const namespace = 'salaryStatisticsModel';
const salaryStatisticsModel = modelFactory.generateModel({ namespace, service });

function getMomentByYearAndMonth(year, month) {
    return year && month ? moment(year * 100 + month, 'YYYYMM') : null;
}

function generateSubTitle(postData) {
    const titleArray = [];
    const { startYear, startMonth, endYear, endMonth } = postData;
    if (startYear && startMonth) {
        titleArray.push(`${startYear}-${(startMonth < 10 ? '0' : '') + startMonth}`);
    }

    if (endYear && endMonth) {
        titleArray.push(`${endYear}-${(endMonth < 10 ? '0' : '') + endMonth}`);
    }
    return titleArray?.length > 0 ? `（${titleArray.join(' ~ ')}）` : '';
}

const EmployeeSalaryCell = connect(({ statisticsModel }) => ({
    organizationCode: statisticsModel.selectOrganizationCode
}))(({ employeeName, employeeCode, organizationCode }) => (
    <>
        {employeeName ? (
            <span
                className={classnames(salaryStyle.linkBtn, salaryStyle.salaryStaticsName)}
                onClick={() => goToSalaryStatisticsDetail({ employeeCode, organizationCode })}
                title={employeeName}
            >
                {employeeName}
            </span>
        ) : (
            <EmptyPlaceHolder />
        )}
    </>
));

Object.assign(salaryStatisticsModel.state, {
    title: '薪资报表【汇总表】',
    subTitle: '',

    columnsRender: columns => {
        const columnProcessor = new ColumnProcessor(
            {
                yearMonth: {
                    width: 120,
                    fixed: true
                },
                employeeName: {
                    width: 132,
                    fixed: true,
                    render(text, record) {
                        return (
                            <EmployeeNameWrapper
                                name={<EmployeeSalaryCell employeeName={text} employeeCode={record.employeeCode} />}
                            />
                        );
                    }
                },
                employeeNo: {
                    width: 100,
                    fixed: true
                }
            },
            CommonColumnInterceptor
        );

        return columnProcessor.merge(columns).filter(item => !item.hidden);
    },

    dataSourceRender: dataSource =>
        [].concat(dataSource).map((item, index) => ({
            id: index,
            ...item,
            ...item.dynamicSalaryPayrollInfo,
            ...item.dynamicEmployeeInfo
        })),

    summaryFieldsRender: renderColumns => {
        const summaryChooser = summaryFieldChooser(
            orFilter(
                // 【数字字段】要汇总
                numberFilter,
                // 【年月字段】要汇总
                col => ({
                    success: col.dataIndex === 'yearMonth',
                    result: { [col.dataIndex]: '合计' }
                })
            )
        );
        return summaryChooser(renderColumns);
    }
});
// 重写effects相关方法
Object.assign(salaryStatisticsModel.effects, {
    // 初始化
    *[modelType.E_INIT](state, { put, call, select, all }) {
        yield put({
            type: modelType.SET_MULTI_STORE,
            payload: { pageLoading: true, searchModel: {} }
        });

        const response = yield call(salaryRecheck.latestSalaryYearMonth, {
            organizationCode: state.payload.organizationCode
        });

        if (isSuccess(response)) {
            const { year, month } = response.data;
            yield put({
                type: modelType.SET_SEARCH_CONDITION,
                payload: {
                    period: [getMomentByYearAndMonth(year, month), getMomentByYearAndMonth(year, month)],
                    startYear: year,
                    startMonth: month,
                    endYear: year,
                    endMonth: month,
                    organizationCode: state.payload.organizationCode
                }
            });
        }

        const postData = yield* modelFactory.searchPostData(select, namespace);

        // 向后台请求【表头】跟【表身】数据
        const [headerResponse, bodyResponse] = yield all([
            // 查询表头数据
            call(service.queryTableHeadData, postData),
            // 查询表身数据
            call(service.queryTableBodyData, postData)
        ]);

        let tableHeader = [];
        if (isSuccess(headerResponse)) {
            tableHeader = headerResponse.data;
        } else {
            message.error(`请求表头数据失败：${headerResponse.msg}`);
        }

        yield put({
            type: modelType.SET_MULTI_STORE,
            payload: {
                tableHeader
            }
        });

        let subTitleStr = '';
        if (isSuccess(bodyResponse)) {
            yield put({
                type: modelType.SET_PAGE_INFO,
                payload: bodyResponse
            });
            subTitleStr = generateSubTitle(postData);
        } else {
            message.error(`请求表身数据失败：${bodyResponse.msg}`);
        }

        yield put({
            type: modelType.SET_MULTI_STORE,
            payload: {
                pageLoading: false,
                subTitle: subTitleStr
            }
        });
    },

    /**
     * 查询
     */
    *[modelType.E_SEARCH](s, { put, call, select, all }) {
        // 设置查询条件
        if (s.payload) {
            yield put({
                type: modelType.SET_SEARCH_CONDITION,
                payload: s.payload
            });
        }

        yield put({
            type: modelType.SET_MULTI_STORE,
            payload: { pageLoading: true }
        });

        const postData = yield* modelFactory.searchPostData(select, namespace);
        if (!s?.fromPagination) {
            postData.page.pageNo = 1;
        }

        // 向后台请求【表头】跟【表身】数据
        const [headerResponse, bodyResponse] = yield all([
            // 查询表头数据
            call(service.queryTableHeadData, postData),
            // 查询表身数据
            call(service.queryTableBodyData, postData)
        ]);

        let tableHeader = [];
        if (isSuccess(headerResponse)) {
            tableHeader = headerResponse.data;
        } else {
            message.error(`请求表头数据失败：${headerResponse.msg}`);
        }

        yield put({
            type: modelType.SET_MULTI_STORE,
            payload: {
                tableHeader
            }
        });

        let subTitleStr = '';
        if (isSuccess(bodyResponse)) {
            yield put({
                type: modelType.SET_PAGE_INFO,
                payload: bodyResponse
            });

            subTitleStr = generateSubTitle(postData);
        } else {
            message.error(`请求表身数据失败：${bodyResponse.msg}`);
        }

        yield put({
            type: modelType.SET_MULTI_STORE,
            payload: {
                pageLoading: false,
                subTitle: subTitleStr
            }
        });
    }
});

export default salaryStatisticsModel;
